package ee.web;

import ee.database.UserService;
import ee.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistrationFilter implements Filter {
  Logger logger = LoggerFactory.getLogger(RegistrationFilter.class);
  @Autowired
  UserService userService;

  public void init(FilterConfig filterConfig) throws ServletException {
    logger.info("-- initialized --");
  }

  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    if (request.getServletPath().contains("registerUser")) {
      User user = new User();
      user.setFirstname(request.getParameter("registeredFirstName"));
      user.setLastname(request.getParameter("registeredLastName"));
      user.setUsername(request.getParameter("registeredUserName"));
      user.setEmail(request.getParameter("registeredEmail"));
      user.setPassword(request.getParameter("registeredPassword"));
      try {
        userService.saveUser(user);
        logger.info("Successfully registered user: " + user.getFirstname() + " " + user.getLastname());
        ((HttpServletResponse) servletResponse).sendRedirect("/");
      } catch (Exception e) {
        logger.warn("Could not register user: " + user.getFirstname() + " " + user.getLastname() + " : " + e.getMessage());
      }
    } else {
      filterChain.doFilter(servletRequest, servletResponse);
    }
  }

  public void destroy() {
  }
}
